<template>
  <div class="login_container">
    <el-form :model="loginFrom" ref="loginRef" :rules="loginRules">
      <div class="avatar_box">
        <img src="@/assets/logo.png" alt="" class="logo" />
      </div>
      <el-form-item prop="username">
        <el-input
          placeholder="请输入内容"
          prefix-icon="el-icon-user-solid"
          v-model.trim="loginFrom.username"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          placeholder="请输入内容"
          prefix-icon="el-icon-lock"
          v-model.trim="loginFrom.password"
          type="password"
        ></el-input>
      </el-form-item>
      <el-form-item style="float: right">
        <el-button type="primary" @click="submitForm">登录</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  data() {
    return {
      loginFrom: {
        username: 'admin',
        password: '123456'
      },
      loginRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {},
  methods: {
    submitForm() {
      this.$refs.loginRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) return false

        const { data: res } = await this.$http.post('login', this.loginFrom)
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('登陆失败')

        this.$message.success('登陆成功')
        window.sessionStorage.setItem('token', res.data.token)
        this.$router.push('/home')
      })
    },
    // 重置表单数据
    resetForm() {
      this.$refs.loginRef.resetFields()
    }
  }
}
</script>
<style lang="less" scoped>
.el-form {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 500px;
  height: 300px;
  box-sizing: border-box;
  background: #fff;
  border-radius: 15px;
  padding: 20px;
  .avatar_box {
    width: 130px;
    height: 130px;
    border-radius: 50%;
    overflow: hidden;
    box-shadow: 0 0 10px #eee;
    margin: -20% auto 0;
    padding: 10px;
    margin-bottom: 20px;
    .logo {
      width: 100%;
      height: 100%;
      background: #eee;
      border-radius: 50%;
    }
  }
}
</style>
